import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/investment_data.dart';

class InvestmentService {
  static const String baseUrl = 'https://api.hrc.com/api/v1';
  static const Duration timeout = Duration(seconds: 30);

  final http.Client client;

  InvestmentService({http.Client? client}) : client = client ?? http.Client();

  /// 获取用户资产总览
  Future<AssetOverview> getAssetOverview(String userId) async {
    try {
      final response = await client
          .get(
            Uri.parse('$baseUrl/investor/assets/overview?userId=$userId'),
            headers: {'Content-Type': 'application/json'},
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          return AssetOverview.fromJson(data['data']);
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to load asset overview: $e');
    }
  }

  /// 获取用户资产列表
  Future<List<UserAsset>> getUserAssets(String userId) async {
    try {
      final response = await client
          .get(
            Uri.parse('$baseUrl/investor/assets?userId=$userId'),
            headers: {'Content-Type': 'application/json'},
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          final assets = data['data'] as List;
          return assets.map((asset) => UserAsset.fromJson(asset)).toList();
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to load user assets: $e');
    }
  }

  /// 获取投资分析数据
  Future<InvestmentAnalysis> getInvestmentAnalysis(String userId) async {
    try {
      final response = await client
          .get(
            Uri.parse('$baseUrl/investor/analysis?userId=$userId'),
            headers: {'Content-Type': 'application/json'},
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          return InvestmentAnalysis.fromJson(data['data']);
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to load investment analysis: $e');
    }
  }

  /// 获取个性化推荐
  Future<PersonalizedRecommendation> getPersonalizedRecommendations(String userId) async {
    try {
      final response = await client
          .get(
            Uri.parse('$baseUrl/investor/recommendations?userId=$userId'),
            headers: {'Content-Type': 'application/json'},
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          return PersonalizedRecommendation.fromJson(data['data']);
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to load recommendations: $e');
    }
  }

  /// 计算投资组合分析
  Future<InvestmentAnalysis> calculatePortfolioAnalysis(List<UserAsset> assets) async {
    try {
      final requestBody = {
        'assets': assets.map((asset) => asset.toJson()).toList(),
      };

      final response = await client
          .post(
            Uri.parse('$baseUrl/investor/analysis/calculate'),
            headers: {'Content-Type': 'application/json'},
            body: json.encode(requestBody),
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          return InvestmentAnalysis.fromJson(data['data']);
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to calculate portfolio analysis: $e');
    }
  }

  /// 刷新资产价格
  Future<List<UserAsset>> refreshAssetPrices(String userId) async {
    try {
      final response = await client
          .post(
            Uri.parse('$baseUrl/investor/assets/refresh-prices'),
            headers: {'Content-Type': 'application/json'},
            body: json.encode({'userId': userId}),
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 200) {
          final assets = data['data'] as List;
          return assets.map((asset) => UserAsset.fromJson(asset)).toList();
        } else {
          throw Exception('API Error: ${data['message']}');
        }
      } else {
        throw Exception('HTTP Error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Failed to refresh asset prices: $e');
    }
  }

  /// 模拟数据（开发环境使用）
  Future<AssetOverview> getMockAssetOverview() async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    return AssetOverview(
      totalValue: 125000.00,
      totalAssets: 15,
      assetBreakdown: {
        AssetType.nft: const AssetSummary(count: 5, value: 80000.00, percentage: 64.0),
        AssetType.stablecoin: const AssetSummary(count: 8, value: 35000.00, percentage: 28.0),
        AssetType.derivative: const AssetSummary(count: 2, value: 10000.00, percentage: 8.0),
      },
      lastUpdated: DateTime.now(),
    );
  }

  /// 模拟投资分析数据
  Future<InvestmentAnalysis> getMockInvestmentAnalysis() async {
    await Future.delayed(const Duration(milliseconds: 500));

    return InvestmentAnalysis(
      totalReturn: 15.8,
      annualizedReturn: 12.5,
      volatility: 8.2,
      riskLevel: RiskLevel.moderate,
      sharpeRatio: 1.25,
      maxDrawdown: 8.5,
      assetCorrelation: {
        'nft_stablecoin': 0.15,
        'nft_derivative': 0.25,
        'stablecoin_derivative': 0.35,
      },
      recommendations: [
        Recommendation(
          id: 'rec_001',
          title: '分散投资风险',
          description: '建议增加稳定币配置比例，降低整体投资组合波动性',
          type: RecommendationType.strategy,
          confidenceScore: 0.85,
          metadata: {
            'target_stablecoin_ratio': 0.35,
            'expected_risk_reduction': 0.15,
          },
        ),
        Recommendation(
          id: 'rec_002',
          title: '关注NFT市场机会',
          description: '当前NFT市场估值合理，建议关注具有文化价值的非遗NFT',
          type: RecommendationType.asset,
          confidenceScore: 0.78,
          metadata: {
            'target_nft_categories': ['cultural', 'heritage'],
            'expected_return': 0.25,
          },
        ),
      ],
      historicalPerformance: [
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 365)), value: 100000),
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 300)), value: 105000),
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 240)), value: 112000),
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 180)), value: 108000),
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 120)), value: 118000),
        PerformanceData(date: DateTime.now().subtract(const Duration(days: 60)), value: 122000),
        PerformanceData(date: DateTime.now(), value: 125000),
      ],
    );
  }

  /// 模拟个性化推荐
  Future<PersonalizedRecommendation> getMockPersonalizedRecommendations() async {
    await Future.delayed(const Duration(milliseconds: 500));

    return PersonalizedRecommendation(
      recommendedAssets: [
        RecommendedAsset(
          id: 'asset_001',
          name: '非遗数字藏品 - 京剧脸谱系列',
          description: '限量发行的京剧脸谱数字藏品，具有深厚的文化价值和收藏潜力',
          type: AssetType.nft,
          expectedReturn: 0.35,
          riskLevel: RiskLevel.moderate,
          confidenceScore: 0.82,
          imageUrl: 'https://example.com/peking-opera.jpg',
        ),
        RecommendedAsset(
          id: 'asset_002',
          name: 'HRC稳定币',
          description: '与非遗生态稳定挂钩的稳定币，适合风险厌恶型投资者',
          type: AssetType.stablecoin,
          expectedReturn: 0.08,
          riskLevel: RiskLevel.low,
          confidenceScore: 0.95,
        ),
      ],
      educationalContent: [
        ContentItem(
          id: 'edu_001',
          title: '非遗NFT投资入门',
          content: '了解如何评估非遗数字藏品的价值和投资潜力...',
          type: 'article',
          difficulty: 'beginner',
          estimatedReadTime: 5,
          thumbnailUrl: 'https://example.com/education-thumb.jpg',
        ),
        ContentItem(
          id: 'edu_002',
          title: '数字资产风险管理',
          content: '学习如何构建平衡的数字资产投资组合...',
          type: 'video',
          difficulty: 'intermediate',
          estimatedReadTime: 15,
        ),
      ],
      marketInsights: [
        MarketInsight(
          id: 'insight_001',
          title: '非遗数字资产市场月报',
          summary: '9月份非遗数字资产市场呈现稳健增长，交易量环比增长15%...',
          category: 'market_overview',
          publishedDate: DateTime.now().subtract(const Duration(days: 1)),
          relevanceScore: 0.92,
        ),
      ],
    );
  }

  void dispose() {
    client.close();
  }
}